package com.burgos.inventory;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class DownloadFile extends Activity implements OnClickListener{

	private ProgressDialog pDialog;
	private static final String GET_LIST = "http://test1984.site11.com/Upload_Docs/getfilelist.php";
	private static final String DOWNLOAD_FILES = "http://test1984.site11.com/Upload_Docs/uploads/";
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_FILES = "files";
	
	private String codename;
	private String names;
	private Button downloadB;
	private String array_spinner[];
	private Spinner spinner;
	private String _path="";
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.download_file);
		//We get the search string from the previews activity
		codename = getIntent().getExtras().getString("keyword");
		
		downloadB = (Button)this.findViewById(R.id.goDownload);
		spinner = (Spinner)this.findViewById(R.id.fileD);

	    downloadB.setOnClickListener(this);
	    
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		new loadFiles().execute();
	}

    @Override
    public void onClick(View v) {
    	switch (v.getId()) {
    	case R.id.goDownload:
    		_path = String.valueOf(spinner.getSelectedItem());
    		Log.i("TESTP",_path);
			if(_path == "null"){
				break;
			}
			//choose to download the selected file, a runnable
			pDialog = ProgressDialog.show(DownloadFile.this, "", "Downloading file...", true);
            new Thread(new Runnable() {
                   public void run() {
                        runOnUiThread(new Runnable() {
                               public void run() {
                               }
                           });                      
                    DownloadSelected(_path);
                   }
                 }).start();
			break;
		default:
			break;
    	}
	}
    
    protected void DownloadSelected(String name) {

  		String fullURL = DOWNLOAD_FILES + codename + "/" + name;
  		String fullPath;
  		try{
  			URL url = new URL(fullURL);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
 
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            //connect
            urlConnection.connect();
            
            //set the path where we want to save the file
            fullPath = Environment.getExternalStorageDirectory() + "/InvDown/" + codename;
            File file = new File(fullPath); 
            if (!file.exists()) {
                file.mkdirs();
            }
            
            File file2 = new File(fullPath, name);
            FileOutputStream fileOutput = new FileOutputStream(file2);
 
            //Stream used for reading the data from the internet
            InputStream inputStream = urlConnection.getInputStream();
 
            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0;
 
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                fileOutput.write(buffer, 0, bufferLength);
            }
            //close the output stream when complete //
            fileOutput.close();
            
  		}catch (final MalformedURLException e) {
            showError("Error : MalformedURLException " + e);        
            e.printStackTrace();
        } catch (final IOException e) {
            showError("Error : IOException " + e);          
            e.printStackTrace();
        }
        catch (final Exception e) {
            showError("Error : Please check your internet connection " + e);
        }
  		
  		pDialog.dismiss();
        Intent i = new Intent(DownloadFile.this, Product.class);
		i.putExtra("keyword",codename);
		finish();
		startActivity(i);
  	}
  	
  	void showError(final String err){
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(DownloadFile.this, err, Toast.LENGTH_LONG).show();
            }
        });
    }
    
    public void UpdateSpinner(){
    	names = names.replace("]", "");
    	names = names.replace("[", "");
    	names = names.replace("\"", "");
		array_spinner = names.split(",");
    	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array_spinner);
        spinner.setAdapter(adapter);
    }
    
  //Class to make the http request and get the product data
  	public class loadFiles extends AsyncTask<String, String, String> {
  		@Override
  		protected void onPreExecute() {
  			super.onPreExecute();
  			pDialog = new ProgressDialog(DownloadFile.this);
  			pDialog.setMessage("Retrieving List of files...");
  			pDialog.setIndeterminate(false);
  			pDialog.setCancelable(true);
  			pDialog.show();
  		}

  		@Override
  		protected String doInBackground(String... arg0) {
  			List<NameValuePair> params = new ArrayList<NameValuePair>();
  			params.add(new BasicNameValuePair("targetID", codename));
  			int success=0;
  			
  			try{
	  			JSONParser jsonParser = new JSONParser();
	  			JSONObject json = jsonParser.makeHttpRequest(GET_LIST, "POST", params);
	  			success = json.getInt(TAG_SUCCESS);
	  			  			
	  			if (success == 1) {
	  				// Get the names form the files and put them on the spinner
		  			names = json.getString(TAG_FILES);		
		  			return null;
	  			}
	  			else {
					return json.getString(TAG_FILES);
				}
  			}catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
  		}

  		@Override
  		protected void onPostExecute(String result) {
  			pDialog.dismiss();
  			if (result != null) {
				Toast.makeText(DownloadFile.this, result, Toast.LENGTH_LONG).show();
  			}
  			else{
  				UpdateSpinner();
  			}
  		}
  	}
}